package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.UserException;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;


    @Override
    public User loadUserByUsername(String username) {
        //根据用户名查询用户的基本信息（密码，用户的权限集合）
        //根据用户名查询用户基本信息
        User user = userMapper.findByUserName(username);
        if (user != null) {
            //根据用户id查用户下面的所有角色
            Set<Role> roles = roleMapper.findByUserId(user.getId());
            user.setRoles(roles);

            //循环角色查询角色下面所有的权限
            if (CollectionUtil.isNotEmpty(roles)) {
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }

        }
        //select c.keyword from t_user_role a left join t_role_permission b
        //														on a.role_id = b.role_id
        //														left join t_permission c
        //														on b.permission_id = c.id
        //where a.user_id = 1
        return user;
    }

    @Override
    public void add(User user) {
        //先获取密码
        String password = user.getPassword();
        //使用bcrypt技术，进行加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String userEncode = encoder.encode(password);
        //再放回user对象中
        user.setPassword(userEncode);
        //1、首先插入用户基本信息,并返回主键
        userMapper.add(user);
        Integer userId = user.getId();
        //2、利用返回的用户主键id和用户勾选的角色id循环建立关系
        //获取用户勾选的角色id
        List<Integer> roleIds = user.getCheckitemIds();
        if (CollectionUtil.isNotEmpty(roleIds)) {
            for (Integer roleId : roleIds) {
                userMapper.setUserAndRole(roleId, userId);//代码可读性强一点
            }
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用分页插件，pageHelper实现分页，底层是mybatis拦截器原理
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据用户输入的查询条件进行查询，跟分页无关
        List<User> users = userMapper.findPage(queryPageBean.getQueryString());
        //返回总记录数和分页数据
        return new PageResult(page.getTotal(), users);
    }

    @Override
    public Map findById4Edit(Integer id) {
        ////返回 用户基本信息，所有的角色，用户勾选的角色id集合 ,
        User user = userMapper.findById(id);
        List<Role> roles = roleMapper.findAll();
        List<Integer> userIds = userMapper.findUserIdAndRoleId(id);
        //定义一个map返回数据
        Map<Object, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("userIds", userIds);
        return map;
    }

    @Override
    public void edit(User user) {
        //1、根据id更新用户基本信息
        userMapper.edit(user);
        //2、先删除原来所有的老关系
        userMapper.deleteAssociation(user.getId());
        //3、然后重新建立新的关系,获取用户勾选的角色id
        List<Integer> roleIds = user.getCheckitemIds();
        if (CollectionUtil.isNotEmpty(roleIds)) {
            userMapper.setUserAndRoleBatch(roleIds, user.getId());
        }
    }

    @Override
    public void delete(Integer id) {
        //先判断当前用户是否被引用
        Integer count = userMapper.findCountUserId(id);
        if (count > 0) {
            //引用了，给用户提示不能删除
            throw new UserException("用户存在引用不能删除！");
        } else {
            //先把用户和角色的中间表相关信息删除
            userMapper.deleteRoleByUserId(id);
            //再删除用户表
            userMapper.delete(id);
        }
    }
}
